﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Security.Cryptography;

namespace Tools
{
    public class Often
    {
        private static readonly byte[] Keys = { 0x82, 0x44, 0x35, 0x38, 0x49, 0xAc, 0xeD, 0xEa };

        /// <summary>
        /// Url加密
        /// </summary>
        /// <param name="str"></param>
        /// <param name="en"></param>
        /// <returns></returns>
        public static string UrlEncode(string str, Encoding en)
        {
            if (str.Trim().Equals("")) return str;
            var sb = new StringBuilder();
            byte[] byStr = en.GetBytes(str);
            foreach (var t in byStr)
            {
                sb.Append(@"%" + Convert.ToString(t, 16));
            }

            return (sb.ToString());
        }

        public static bool IsPublicNull(object t)
        {
            PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
            return (from item in properties let name = item.Name select item.GetValue(t, null)).Any(value => value == null);
        }
        /// <summary>
        /// 去除HTML标记
        /// </summary>
        /// <param name="htmlstring"></param>
        /// <returns></returns>
        public static string MoveHtml(string htmlstring)
        {
            //删除脚本
            htmlstring = Regex.Replace(htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            //删除HTML
            htmlstring = Regex.Replace(htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(\s+);", "", RegexOptions.IgnoreCase);
            htmlstring = htmlstring.Replace("<", "");
            htmlstring = htmlstring.Replace(">", "");
            htmlstring = htmlstring.Replace("\r", "");
            htmlstring = htmlstring.Replace("\n", "");
            htmlstring = htmlstring.Replace(@"\", "");
            htmlstring = htmlstring.Replace('"'.ToString(), "");
            return htmlstring;
        }

        /// <summary> 
        /// 转换人民币大小金额 
        /// </summary> 
        /// <param name="num">金额</param> 
        /// <returns>返回大写形式</returns> 
        public static string RmbParse(decimal num)
        {
            const string str1 = "零壹贰叁肆伍陆柒捌玖"; //0-9所对应的汉字 
            string str2 = "万仟佰拾亿仟佰拾万仟佰拾元角分"; //数字位所对应的汉字 
            string str5 = "";  //人民币大写金额形式 
            int i;    //循环变量 
            string ch2 = "";    //数字位的汉字读法 
            int nzero = 0;  //用来计算连续的零值是几个 

            num = Math.Round(Math.Abs(num), 2);    //将num取绝对值并四舍五入取2位小数 
            string str4 = ((long)(num * 100)).ToString();
            int j = str4.Length;
            if (j > 15) { return "溢出"; }
            str2 = str2.Substring(15 - j);   //取出对应位数的str2的值。如：200.55,j为5所以str2=佰拾元角分 

            //循环取出每一位需要转换的值 
            for (i = 0; i < j; i++)
            {
                string str3 = str4.Substring(i, 1);    //从原num值中取出的值 
                int temp = Convert.ToInt32(str3);            //从原num值中取出的值 
                string ch1;    //数字的汉语读法 
                if (i != (j - 3) && i != (j - 7) && i != (j - 11) && i != (j - 15))
                {
                    //当所取位数不为元、万、亿、万亿上的数字时 
                    if (str3 == "0")
                    {
                        ch1 = "";
                        ch2 = "";
                        nzero = nzero + 1;
                    }
                    else
                    {
                        if (str3 != "0" && nzero != 0)
                        {
                            ch1 = "零" + str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                        else
                        {
                            ch1 = str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                    }
                }
                else
                {
                    //该位是万亿，亿，万，元位等关键位 
                    if (str3 != "0" && nzero != 0)
                    {
                        ch1 = "零" + str1.Substring(temp * 1, 1);
                        ch2 = str2.Substring(i, 1);
                        nzero = 0;
                    }
                    else
                    {
                        if (str3 != "0" && nzero == 0)
                        {
                            ch1 = str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                        else
                        {
                            if (str3 == "0" && nzero >= 3)
                            {
                                ch1 = "";
                                ch2 = "";
                                nzero = nzero + 1;
                            }
                            else
                            {
                                if (j >= 11)
                                {
                                    ch1 = "";
                                    nzero = nzero + 1;
                                }
                                else
                                {
                                    ch1 = "";
                                    ch2 = str2.Substring(i, 1);
                                    nzero = nzero + 1;
                                }
                            }
                        }
                    }
                }
                if (i == (j - 11) || i == (j - 3))
                {
                    //如果该位是亿位或元位，则必须写上 
                    ch2 = str2.Substring(i, 1);
                }
                str5 = str5 + ch1 + ch2;

                if (i == j - 1 && str3 == "0")
                {
                    //最后一位（分）为0时，加上“整” 
                    str5 = str5 + '整';
                }
            }
            if (num == 0)
            {
                str5 = "零元整";
            }
            return str5;
        }

        /// <summary> 
        /// 一个重载，将字符串先转换成数字在调用CmycurD(decimal num) 
        /// </summary>
        /// <returns></returns> 
        public static string RmbParse(string str)
        {
            try
            {
                decimal num = Convert.ToDecimal(str);
                return RmbParse(num);
            }
            catch
            {
                return "非数字形式！";
            }
        }

        /// <summary>
        /// 转换Html换行代码
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string HtmlParse(string text)
        {
            text = text.Replace('"', '“');
            text = text.Replace("'", "‘");
            text = text.Replace("\r", "&nbsp;&nbsp;");
            text = text.Replace("\n", "<br/>");
            return text;
        }

        /// <summary>
        /// 获取当前时间 000000000格式
        /// </summary>
        /// <returns></returns>
        public static long UnixTime()
        {
            return UnixTime(DateTime.Now);
        }

        /// <summary>
        /// 获取当前时间 000000000格式
        /// </summary>
        public static long UnixTime(DateTime date)
        {
            return (date.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
        }

        /// <summary>
        /// MD5　32位加密
        /// </summary>
        public static string EncryptMd5(string input, Encoding encoding = null)
        {
            var md5 = new MD5CryptoServiceProvider();
            encoding = encoding ?? Encoding.GetEncoding("GB2312");
            byte[] inBytes = encoding.GetBytes(input);
            byte[] outBytes = md5.ComputeHash(inBytes);
            string outString = "";
            for (int i = 0; i < outBytes.Length; i++)
            {
                outString += outBytes[i].ToString("x2");
            }
            return outString;
        }

        /// <summary>
        /// 字符串转换数组
        /// </summary>
        public static List<string> StringToArray(string txt, char sepeater)
        {
            string[] ss = txt.Split(sepeater);
            return ss.Where(s => !string.IsNullOrEmpty(s) && s != sepeater.ToString()).ToList();
        }

        /// <summary>
        /// 数组转换字符串
        /// </summary>
        public static string ArrayToString(List<string> list, string speater)
        {
            var sb = new StringBuilder();
            for (int i = 0; i < list.Count; i++)
            {
                if (i == list.Count - 1)
                {
                    sb.Append(list[i]);
                }
                else
                {
                    sb.Append(list[i]);
                    sb.Append(speater);
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 转全角的函数(SBC case)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string FormatSbc(string input)
        {
            //半角转全角：
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 32)
                {
                    c[i] = (char)12288;
                    continue;
                }
                if (c[i] < 127)
                    c[i] = (char)(c[i] + 65248);
            }
            return new string(c);
        }

        /// <summary>
        ///  转半角的函数(SBC case)
        /// </summary>
        /// <param name="input">输入</param>
        /// <returns></returns>
        public static string FormatDbc(string input)
        {
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 12288)
                {
                    c[i] = (char)32;
                    continue;
                }
                if (c[i] > 65280 && c[i] < 65375)
                    c[i] = (char)(c[i] - 65248);
            }
            return new string(c);
        }

        /// <summary>
        ///  将字符串样式转换为纯字符串
        /// </summary>
        /// <param name="strList"></param>
        /// <param name="splitString"></param>
        /// <returns></returns>
        public static string CleanStyle(string strList, string splitString)
        {
            string retrunValue;
            //如果为空，返回空值
            if (strList == null)
            {
                retrunValue = "";
            }
            else
            {
                //返回去掉分隔符
                string newString = strList.Replace(splitString, "");
                retrunValue = newString;
            }
            return retrunValue;
        }

        /// <summary>
        /// 将字符串转换为新样式
        /// </summary>
        /// <param name="list"></param>
        /// <param name="newStyle"></param>
        /// <param name="splitString"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public static string NewStyle(string list, string newStyle, string splitString, out string error)
        {
            string returnValue;
            //如果输入空值，返回空，并给出错误提示
            if (list == null)
            {
                returnValue = "";
                error = "请输入需要划分格式的字符串";
            }
            else
            {
                //检查传入的字符串长度和样式是否匹配,如果不匹配，则说明使用错误。给出错误信息并返回空值
                int strListLength = list.Length;
                int newStyleLength = CleanStyle(newStyle, splitString).Length;
                if (strListLength != newStyleLength)
                {
                    returnValue = "";
                    error = "样式格式的长度与输入的字符长度不符，请重新输入";
                }
                else
                {
                    //检查新样式中分隔符的位置
                    string lengstr = "";
                    for (int i = 0; i < newStyle.Length; i++)
                    {
                        if (newStyle.Substring(i, 1) == splitString)
                        {
                            lengstr = lengstr + "," + i;
                        }
                    }
                    if (lengstr != "")
                    {
                        lengstr = lengstr.Substring(1);
                    }
                    //将分隔符放在新样式中的位置
                    string[] str = lengstr.Split(',');
                    list = str.Aggregate(list, (current, bb) => current.Insert(int.Parse(bb), splitString));
                    //给出最后的结果
                    returnValue = list;
                    //因为是正常的输出，没有错误
                    error = "";
                }
            }
            return returnValue;
        }

        /// <summary>
        /// 删除最后结尾的一个逗号
        /// </summary>
        public static string DelLastComma(string str)
        {
            return str.Substring(0, str.LastIndexOf(","));
        }

        /// <summary>
        /// 删除最后结尾的指定字符后的字符
        /// </summary>
        public static string DelLastChar(string str, string strchar)
        {
            return str.Substring(0, str.LastIndexOf(strchar));
        }

        /// <summary>
        /// 对比当前时间比输入时间
        /// </summary>
        /// <param name="time">输入时间</param>
        /// <param name="s">对比增量（秒）</param>
        /// <returns></returns>
        public static bool DateTimeContrast(DateTime time, int s)
        {
            var v1 = UnixTime(time.AddSeconds(s));
            var v2 = UnixTime(DateTime.Now);
            return !(v1 > v2);
        }

        /// <summary>
        /// 数字分组
        /// </summary>
        /// <param name="count">总数</param>
        /// <param name="num">分组数</param>
        /// <returns></returns>
        public static Dictionary<int, int> DigitalPacket(int count, int num)
        {
            num = count <= num ? count : num;
            int die = count % num;
            int increment = (count - die) / (die == 0 ? num : num - 1);
            var array = new Dictionary<int, int>();
            int counter = 0;
            for (int i = 0; ; i++)
            {
                int temp = counter + increment;
                if (i >= num - 1)
                {
                    array.Add(counter, count);
                    break;
                }
                array.Add(counter, temp);
                counter = temp;
            }
            return array;
        }

        /// <summary>
        /// 把秒转换成分钟
        /// </summary>
        /// <returns></returns>
        public static int SecondToMinute(int second)
        {
            var mm = second / (decimal)60;
            return Convert.ToInt32(Math.Ceiling(mm));
        }

        #region 返回某年某月最后一天
        /// <summary>
        /// 返回某年某月最后一天
        /// </summary>
        /// <param name="year">年份</param>
        /// <param name="month">月份</param>
        /// <returns>日</returns>
        public static int GetMonthLastDate(int year, int month)
        {
            var lastDay = new DateTime(year, month, new System.Globalization.GregorianCalendar().GetDaysInMonth(year, month));
            int day = lastDay.Day;
            return day;
        }
        #endregion

        #region 返回时间差
        public static string DateDiff(DateTime dateTime1, DateTime dateTime2)
        {
            string dateDiff;

            TimeSpan ts = dateTime2 - dateTime1;
            if (ts.Days >= 1)
            {
                dateDiff = dateTime1.Month.ToString() + "月" + dateTime1.Day.ToString() + "日";
            }
            else
            {
                if (ts.Hours > 1)
                {
                    dateDiff = ts.Hours.ToString() + "小时前";
                }
                else
                {
                    dateDiff = ts.Minutes.ToString() + "分钟前";
                }
            }
            return dateDiff;
        }
        #endregion

        /// <summary>
        /// 获取指定值
        /// </summary>
        public static string SpecifiedValue(string content, string start, string end, string trim = "", bool lower = false)
        {
            content = lower ? trim.Equals("") ? content : content.ToLower().Replace(trim, string.Empty) : trim.Equals("") ? content : content.Replace(trim, string.Empty);
            start = lower ? start.ToLower() : start;
            end = lower ? end.ToLower() : end;
            string doc;
            try
            {
                doc = Regex.Split(content, start)[1];
                doc = end.Trim().Equals(string.Empty) ? doc : Regex.Split(doc, end)[0];
            }
            catch (Exception) { return string.Empty; }
            return doc.Trim();
        }

        /// <summary>
        /// 获取指定值
        /// </summary>
        public static string SpecifiedValueNoreg(string content, string start, string end, string trim = "", bool lower = false)
        {
            content = lower ? trim.Equals("") ? content : content.ToLower().Replace(trim, string.Empty) : trim.Equals("") ? content : content.Replace(trim, string.Empty);
            start = lower ? start.ToLower() : start;
            end = lower ? end.ToLower() : end;
            string doc;
            try
            {
                doc = content.Split(new string[] { start }, StringSplitOptions.None)[1];
                doc = end.Trim().Equals(string.Empty) ? doc : doc.Split(new string[] { end }, StringSplitOptions.None)[0];
            }
            catch (Exception) { return string.Empty; }
            return doc.Trim();
        }

        public static CookieContainer CookieFormat(string cookieStr, string domain)
        {
            var myCookieContainer = new CookieContainer();
            string[] cookstr = cookieStr.Split(';');
            foreach (string str in cookstr)
            {
                if (str.Trim().Equals(string.Empty)) continue;
                string[] cookieNameValue = str.Split('=');
                var ck = new Cookie(cookieNameValue[0].Trim(), cookieNameValue[1].Trim()) { Domain = domain };
                myCookieContainer.Add(ck);
            }
            return myCookieContainer;
        }

        /// <summary>
        /// 是否所有的属性不为null
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public static bool IsAttributeNull(object t)
        {
            PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
            return (from item in properties let name = item.Name select item.GetValue(t, null)).All(value => value != null);
        }

        #region 加密
        /// <summary> 
        /// DES加密字符串 
        /// </summary> 
        /// <param name="encryptString">待加密的字符串</param> 
        /// <param name="encryptKey">加密密钥,要求为8位</param> 
        /// <returns>加密成功返回加密后的字符串，失败返回源串</returns> 
        public static string EncryptDes(string encryptString, string encryptKey)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
                byte[] rgbIv = Keys;
                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
                var dCSP = new DESCryptoServiceProvider();
                var mStream = new MemoryStream();
                var cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIv), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
            catch
            {
                return encryptString;
            }
        }

        /// <summary> 
        /// DES解密字符串 
        /// </summary> 
        /// <param name="decryptString">待解密的字符串</param> 
        /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param> 
        /// <returns>解密成功返回解密后的字符串，失败返源串</returns> 
        public static string DecryptDes(string decryptString, string decryptKey)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
                byte[] rgbIv = Keys;
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                var dcsp = new DESCryptoServiceProvider();
                var mStream = new MemoryStream();
                var cStream = new CryptoStream(mStream, dcsp.CreateDecryptor(rgbKey, rgbIv), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch
            {
                return decryptString;
            }
        }
        #endregion

        public static KeyValuePair<string, string>[] UrlDataToKeyValuePair(string data)
        {
            var array = data.Split('&').Select(v => v.Split('=')).Where(sc => sc.Length == 2).ToDictionary(sc => sc[0].Trim(), sc => sc[1].Trim());
            var result = (from v in array orderby v.Key select v).ToArray();
            return result;
        }

        public static string RandPhoneNumber()
        {
            var v1 = new string[] { "130", "131", "132", "133", "134", "135", "136", "137", "138", "139", "150", "151", "152", "153", "158", "159", "180", "188", "189" };
            string v11 = v1[new Random().Next(0, v1.Length - 1)];
            string v2 = string.Format("{0}{1}", v11, new Random().Next(10000000, 99999999));
            return v2;
        }

        public static string SubString(string str, int len)
        {
            if (str == null || str.Length <= len) return str;
            else return str.Substring(0, len - 2) + "..";
        }

        public static string RandomKey(string key, int num = 8)
        {
            string md5 = Often.EncryptMd5(key + DateTime.Now.ToString("mmyyDDssMMyyHH"));
            return "_" + md5.Substring(0, num);
        }

        public static string RandomOrderId(int num = 16)
        {
            string str = DateTime.Now.ToString("mmyyddssMMyyHHff");
            return str.Substring(0, num);
        }
    }
}
